from datetime import datetime
from app import db
import json


class UserBehavior(db.Model):
    """用户行为记录表"""
    __tablename__ = 'user_behaviors'
    
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, comment='操作用户ID')
    target_user_id = db.Column(db.Integer, db.ForeignKey('users.id'), comment='目标用户ID')
    action = db.Column(db.String(50), nullable=False, comment='行为类型')
    extra_data = db.Column(db.Text, comment='额外数据JSON')
    ip_address = db.Column(db.String(45), comment='IP地址')
    user_agent = db.Column(db.String(500), comment='用户代理')
    
    # 时间戳
    created_at = db.Column(db.DateTime, default=datetime.utcnow, comment='创建时间')
    
    # 显式定义关系，避免外键歧义
    __table_args__ = (
        db.Index('idx_user_id', 'user_id'),
        db.Index('idx_target_user_id', 'target_user_id'),
        db.Index('idx_action', 'action'),
        db.Index('idx_created_at', 'created_at'),
    )
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'user_id': self.user_id,
            'target_user_id': self.target_user_id,
            'action': self.action,
            'extra_data': json.loads(self.extra_data) if self.extra_data else None,
            'ip_address': self.ip_address,
            'user_agent': self.user_agent,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None
        }
    
    def set_extra_data(self, data):
        """设置额外数据"""
        if data:
            self.extra_data = json.dumps(data, ensure_ascii=False)
    
    def get_extra_data(self):
        """获取额外数据"""
        if self.extra_data:
            return json.loads(self.extra_data)
        return None
    
    def __repr__(self):
        return f'<UserBehavior {self.action}>' 